//imageUtils.ts 

const base64ToBlob = (data: any) => {
  var arr = data.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

export const CompressImage: any = (src: any, width: number) => {

  return new Promise((resolve) => {

    const img = new Image();
    img.src = src;

    let cvs = document.createElement("canvas");

    img.onload = function () {
      let ratio = img.naturalWidth / img.naturalHeight; //  获取原图比例,为了等比压缩
      cvs.width = width;
      cvs.height = cvs.width / ratio;
      let ctx: any = cvs.getContext('2d');
      ctx.drawImage(img, 0, 0, cvs.width, cvs.height);    //  画在 canvas 上
      // 压缩后新图的 base64
      let zipBase64 = base64ToBlob(cvs.toDataURL());
      resolve(zipBase64);

    }

  })

}